package com.hellohoper.assembly.common.utils.util;


import org.slf4j.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.MarshalException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Created by hk on 9/30/16.
 */
public class XmlUtils {

    private static Logger logger = org.slf4j.LoggerFactory.getLogger(XmlUtils.class);

    private XmlUtils() {
        throw new IllegalAccessError("Utility class");
    }

    public static String marshal(Object object) throws MarshalException {
        StringWriter writer = null;
        try {
            writer = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.marshal(object, writer);
            writer.flush();
        } catch (Exception e) {
            throw new MarshalException(e);
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        return writer.toString();
    }

    public static String marshal(Object object, Class classes[]) throws MarshalException {
        StringWriter writer = null;
        try {
            writer = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(classes);
            Marshaller marshaller = context.createMarshaller();
            marshaller.marshal(object, writer);
            writer.flush();
        } catch (Exception e) {
            throw new MarshalException(e);
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (Exception e) {
                logger.error("", e);
            }
        }
        return writer.toString();
    }

    public static Object unMarshal(String str, Class class1) throws MarshalException {
        StringReader reader = null;
        Object object = null;
        try {
            reader = new StringReader(str);
            JAXBContext context = JAXBContext.newInstance(class1);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            object = unmarshaller.unmarshal(reader);
        } catch (Exception e) {
            throw new MarshalException(e);
        } finally {
            if (reader != null)
                reader.close();
        }

        return object;
    }
}
